#include <stdio.h>
#include <stdlib.h>
#include "wc.h"

void wc_file(const char *filename) {
    FILE *file;
    int lines = 0, words = 0, bytes = 0;
    int in_word = 0;
    char ch;

    if ((file = fopen(filename, "r")) == NULL) {
        perror("fopen");
        return;
    }

    while ((ch = fgetc(file)) != EOF) {
        bytes++;
        if (ch == '\n') {
            lines++;
        }
        if (ch == ' ' || ch == '\n' || ch == '\t') {
            in_word = 0;
        } else if (in_word == 0) {
            in_word = 1;
            words++;
        }
    }

    fclose(file);
    printf("%d %d %d %s\n", lines, words, bytes, filename);
}

int wc_main(int argc, char *argv[]) {
    if (argc < 2) {
        fprintf(stderr, "Usage: wc <file>\n");
        return 1;
    }

    for (int i = 1; i < argc; ++i) {
        wc_file(argv[i]);
    }

    return 0;
}
